package com.shuohe.controller.develop.url;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shuohe.dao.develop.url.UrlDao;
import com.shuohe.dao.develop.url.UrlIutputParaDao;
import com.shuohe.dao.develop.url.UrlOutputParaDao;
import com.shuohe.entity.develop.url.Url;
import com.shuohe.entity.develop.url.UrlIutputPara;
import com.shuohe.entity.develop.url.UrlOutputPara;
import com.shuohe.service.util.sql.EasyuiServiceImpl;
import com.shuohe.service.util.sql.SqlServiceImpl;
import com.shuohe.util.db.DbQuerySql;
import com.shuohe.util.easyuiBean.EasyUiCombobox;
import com.shuohe.util.easyuiBean.EasyUiDataGrid;
import com.shuohe.util.json.Json;
import com.shuohe.util.returnBean.ReturnBean;

@Controller  
@RequestMapping("/develop/url/*")  
public class UrlController {
	
	@Autowired
	private UrlDao urlDao; 
	@Autowired
	private UrlIutputParaDao urlIutputParaDao; 
	@Autowired
	private UrlOutputParaDao urlOutputParaDao; 
	
	@Resource
	private EasyuiServiceImpl easyUiDto;
	
	@Resource
	private SqlServiceImpl sqlServiceImpl;
	
	private Logger logger = LoggerFactory.getLogger(UrlController.class);
		
	@RequestMapping(value="getByPid.do")  
    public @ResponseBody List<Url> getByPid(HttpServletRequest request,HttpServletResponse response){
		String pid=request.getParameter("pid");
		return urlDao.findByPid(Integer.parseInt(pid));
	}
	
	/**
	 * 保存url及其相关实例
	 * @param request
	 * @param response
	 * @return
	 */
	@Transactional
	@RequestMapping(value="save.do")  
    public @ResponseBody ReturnBean save(HttpServletRequest request,HttpServletResponse response){
		
		Gson reGson = new Gson();

		String url_ = request.getParameter("url").replaceAll("\"\"", "null");
		String UrlIutputPara_ = request.getParameter("UrlIutputPara").replaceAll("\"\"", "null");
//		String UrlOutputPara_ = request.getParameter("UrlOutputPara").replaceAll("\"\"", "null");
					
		Url url = (Url) Json.toObject(Url.class, url_);		
		ArrayList<UrlIutputPara> UrlIutputPara_list = reGson.fromJson(UrlIutputPara_, new TypeToken<ArrayList<UrlIutputPara>>(){}.getType());
//		ArrayList<UrlOutputPara> UrlOutputPara_list = reGson.fromJson(UrlOutputPara_, new TypeToken<ArrayList<UrlOutputPara>>(){}.getType());
			
	
		
		try 
		{			
			Url check = urlDao.findByName(url.getName());
			if(check!=null)
			{
				return new ReturnBean(false,"Url名称重复，请换个试试");
			}
			
			
			Url url_x = urlDao.save(url);
			
			ArrayList<UrlIutputPara> i_list = new ArrayList<UrlIutputPara>();
			for(UrlIutputPara i:UrlIutputPara_list)
			{
				i.setPid(url_x.getId());
				i_list.add(i);
			}
//			ArrayList<UrlOutputPara> o_list = new ArrayList<UrlOutputPara>();
//			for(UrlOutputPara o:UrlOutputPara_list)
//			{
//				o.setPid(url_x.getId());
//				o_list.add(o);
//			}		
			
			
			urlIutputParaDao.save(i_list);
//			urlOutputParaDao.save(o_list);
			
			return new ReturnBean(true,"");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return new ReturnBean(false,e.getMessage());
		}
		
	}
	
	
	@Transactional
	@RequestMapping(value="update.do")  
    public @ResponseBody ReturnBean update(HttpServletRequest request,HttpServletResponse response){
		
		Gson reGson = new Gson();

		String url_ = request.getParameter("url").replaceAll("\"\"", "null");
		String UrlIutputPara_ = request.getParameter("UrlIutputPara").replaceAll("\"\"", "null");
//		String UrlOutputPara_ = request.getParameter("UrlOutputPara").replaceAll("\"\"", "null");
					
		Url url = (Url) Json.toObject(Url.class, url_);		
		ArrayList<UrlIutputPara> UrlIutputPara_list = reGson.fromJson(UrlIutputPara_, new TypeToken<ArrayList<UrlIutputPara>>(){}.getType());
//		ArrayList<UrlOutputPara> UrlOutputPara_list = reGson.fromJson(UrlOutputPara_, new TypeToken<ArrayList<UrlOutputPara>>(){}.getType());
			
		ArrayList<UrlIutputPara> i_list = new ArrayList<UrlIutputPara>();
		for(UrlIutputPara i:UrlIutputPara_list)
		{
			i.setPid(url.getId());
			i_list.add(i);
		}
//		ArrayList<UrlOutputPara> o_list = new ArrayList<UrlOutputPara>();
//		for(UrlOutputPara o:UrlOutputPara_list)
//		{
//			o.setPid(url.getId());
//			o_list.add(o);
//		}		
		try 
		{			
			urlDao.save(url);
			urlIutputParaDao.deleteByPid(url.getId());	
			urlOutputParaDao.deleteByPid(url.getId());
			
			urlIutputParaDao.save(i_list);
//			urlOutputParaDao.save(o_list);
			
			return new ReturnBean(true,"");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return new ReturnBean(false,e.getMessage());
		}
		
	}
	
	
	/**
	 * 删除Url
	 * @param request
	 * @param response
	 * @return
	 */
	@Transactional
	@RequestMapping(value="delete.do")  
    public @ResponseBody ReturnBean delete(HttpServletRequest request,HttpServletResponse response){
		
		String _id = request.getParameter("id").replaceAll("\"\"", "null");	
		try 
		{			
			int id = Integer.parseInt(_id);
			urlDao.deleteById(id);
			urlIutputParaDao.deleteByPid(id);	
			urlOutputParaDao.deleteByPid(id);
			
			return new ReturnBean(true,"删除成功");
		}
		catch(NumberFormatException e)
		{
			e.printStackTrace();
			return new ReturnBean(false,"传递的数据错误");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return new ReturnBean(false,e.getMessage());
		}
		
	}
	
	
	
	@RequestMapping(value="findUrlById.do")  
    public @ResponseBody Url findUrlById(HttpServletRequest request,HttpServletResponse response){
		String id=request.getParameter("id");
		return urlDao.findById(Integer.parseInt(id));
	}
	
	@RequestMapping(value="findUrlSqlById.do",produces="text/html; charset=UTF-8")  
    public @ResponseBody String findUrlSqlById(HttpServletRequest request,HttpServletResponse response){
		String id=request.getParameter("id");
		Url url =  urlDao.findById(Integer.parseInt(id));
		return url.getSql_str();
	}
	
	
	@RequestMapping(value="findUrlIutputParaByPid.do")  
    public @ResponseBody List<UrlIutputPara> findUrlIutputParaById(HttpServletRequest request,HttpServletResponse response){
		String pid=request.getParameter("pid");
		return urlIutputParaDao.findByPid(Integer.parseInt(pid));
	}
	
	@RequestMapping(value="findUrlOutputParaByPid.do")  
    public @ResponseBody List<UrlOutputPara> findUrlOutputParaById(HttpServletRequest request,HttpServletResponse response){
		String pid=request.getParameter("pid");
		return urlOutputParaDao.findByPid(Integer.parseInt(pid));
	}
	

	private class UrlVo implements Serializable
	{
		int id;
		String name;
		String disc;
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getDisc() {
			return disc;
		}
		public void setDisc(String disc) {
			this.disc = disc;
		}
		
		
	}
	@RequestMapping(value="getAllUrl.do")  
    public @ResponseBody List<UrlVo> getAllUrl(HttpServletRequest request,HttpServletResponse response){
		List<Url> url = urlDao.findAll();
		List<UrlVo> UrlVoList = new ArrayList<UrlVo>(); 
		for(Url u:url)
		{
			UrlVo ur = new UrlVo();
			ur.setId(u.getId());
			ur.setDisc(u.getDescr());
			ur.setName(u.getName());
			UrlVoList.add(ur);
		}
		return UrlVoList;
	}
	
	
	private class UrlInfoVo
	{
		public Url url = new Url();
		public List<UrlIutputPara> urlIutputPara = new ArrayList<UrlIutputPara>();
		public List<UrlOutputPara> urlOutputPara = new ArrayList<UrlOutputPara>();
		public void setUrl(Url url) {
			this.url = url;
		}
		public void setUrlIutputPara(List<UrlIutputPara> urlIutputPara) {
			this.urlIutputPara = urlIutputPara;
		}
		public void setUrlOutputPara(List<UrlOutputPara> urlOutputPara) {
			this.urlOutputPara = urlOutputPara;
		}		
	}
	@RequestMapping(value="getUrlById.do")  
	  public @ResponseBody UrlInfoVo getUrlById(HttpServletRequest request,HttpServletResponse response){
			String id=request.getParameter("id");
			System.out.println("id = "+id);
			Url url = urlDao.findById(Integer.parseInt(id));
	//			System.out.println("id = "+Json.toJsonByPretty(url.getId()));
			UrlInfoVo vo = new UrlInfoVo();
			vo.url.setId(url.getId());
			vo.url.setName(url.getName());
			vo.url.setDescr(url.getDescr());		
			vo.setUrlIutputPara(urlIutputParaDao.findByPid(url.getId()));
			vo.setUrlOutputPara(urlOutputParaDao.findByPid(url.getId()));
			
			return vo;
		}
	
	
	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="getUrl.do")  
    public @ResponseBody Object getUrl(HttpServletRequest request,HttpServletResponse response){
		String name=request.getParameter("name");
		
		Url url = urlDao.findByName(name);
		List<UrlIutputPara> input_list= urlIutputParaDao.findByPid(url.getId());		
		String sql = url.getSql_str();
		logger.info("输入参数数量 = "+input_list.size());
		
		
		
		for(Object o:input_list)
		{
			UrlIutputPara u = (UrlIutputPara)o;
			String key = u.getSql_para_name();
			String value = request.getParameter(u.getName());
			String expr = u.getType();
			boolean is_necessary = u.isIs_necessary();
			logger.info("is_necessary = "+is_necessary);
			
			if("date>=".equals(expr))
			{
				if(is_necessary)
					sql += DbQuerySql.andDateAGreatThanBNecessary(key, value);
				else
					sql += DbQuerySql.andDateAGreatThanB(key, value);		
			}
			else if("date<=".equals(expr))
			{
				if(is_necessary)		
					sql += DbQuerySql.andDateALessrThanBNecessary(key, value);
				else		
					sql += DbQuerySql.andDateALessrThanB(key, value);
			}
			else if(">".equals(expr))
			{
				if(is_necessary)		
					sql += DbQuerySql.andAGreaterThanBNecessary(key, value);	
				else
					sql += DbQuerySql.andAGreaterThanB(key, value);	
			}
			else if("<".equals(expr))
			{
				if(is_necessary)
					sql += DbQuerySql.andALessThanBNecessary(key, value);
				else
					sql += DbQuerySql.andALessThanB(key, value);
			}
			else if("=".equals(expr))
			{
				if(is_necessary)
					sql += DbQuerySql.andAEqualToBNecessary(key, value);
				else
					sql += DbQuerySql.andAEqualToB(key, value);
			}
			else if("like".equals(expr))
			{
				sql += DbQuerySql.andALikeB(key, value);
			}
		}
			
//		logger.info(sql);
		
		//拼接sql排序的语句
		if(null!=url.getArrange_str()){
			sql += "\r\n";
			sql += url.getArrange_str();
		}
		
		logger.info(sql);		

			if("easyui-combobox".equals(url.getType()))
			{
				try {
					return easyUiDto.getEasyUiCombobox(sql);
				} catch (Exception e) {					
					e.printStackTrace();
					return new EasyUiCombobox();
				}
			}
			else if("easyui-datagrid".equals(url.getType()))
			{
				String sql_count="";
				sql_count = sql;
				
				String page = request.getParameter("page");
				String rows = request.getParameter("rows");
				sql += DbQuerySql.limit(page, rows);
								
				try { 
					EasyUiDataGrid dg = easyUiDto.getEasyUiDataGrid(sql,sql_count);
					HttpSession session = request.getSession(true);
					session.setAttribute("searchResult", dg.getRows());//将获取到的数据存入session
					return dg;
				} catch (Exception e) {					
					e.printStackTrace();
					return new EasyUiDataGrid(0,null);
				}
				
			}
			else if("Object".equals(url.getType()))
			{
				try {
					return sqlServiceImpl.getDataForOneItem(sql);
				} catch (Exception e) {					
					e.printStackTrace();
					return null;
				}
			}
			else if("List-Object".equals(url.getType()))
			{
				try {
					return easyUiDto.getEasyUiCombobox(sql);
				} catch (Exception e) {					
					e.printStackTrace();
					return new EasyUiCombobox();
				}
			}
			else
				return null;

	}
	
	
}
